<template>
  <div>
    <el-card v-loading="inLoading">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            v-model="keyword"
            @clear="queryInfo.keyword=keyword"
            clearable
            placeholder="请输入内容"
          >
            <el-button @click="queryInfo.keyword=keyword" slot="append" icon="el-icon-search"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button @click="showUpdateDialog()" type="primary">添加用户</el-button>
        </el-col>
      </el-row>
      <el-table :data="userList" border stripe style="width: 100%">
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="user" label="用户名"></el-table-column>
        <el-table-column prop="limit" label="角色">
          <template slot-scope="scope">
            <div>
              <el-tag
                v-for="(value,key,i) in $app.user.limitType"
                :type="['','success','danger','warning','info'][i]"
                :key="value"
                v-show="scope.row.limit==value"
              >{{$app.user.limit[value]}}</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <el-tooltip effect="dark" content="编辑" :enterable="false" placement="top">
              <el-button
                @click="showUpdateDialog(scope.row)"
                type="primary"
                icon="el-icon-edit"
                size="mini"
                :disabled="scope.row.user=='admin'"
              ></el-button>
            </el-tooltip>
            <el-tooltip effect="dark" content="重置密码" :enterable="false" placement="top">
              <el-button
                @click="resetPassword(scope.row.user)"
                type="warning"
                icon="el-icon-key"
                size="mini"
                :disabled="scope.row.user=='admin'"
              ></el-button>
            </el-tooltip>
            <el-tooltip effect="dark" content="删除" :enterable="false" placement="top">
              <el-button
                @click="removeUser(scope.row.user)"
                type="danger"
                icon="el-icon-delete"
                size="mini"
                :disabled="scope.row.user=='admin'"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="size=>{queryInfo.pageSize = size}"
        @current-change="page=>{queryInfo.page = page}"
        :current-page="queryInfo.page"
        :page-sizes="[5, 10, 20, 30]"
        :page-size="queryInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>
    <el-dialog
      :title="updateForm.isCreate?'添加用户':'修改用户'"
      :visible.sync="updateDialogVisible"
      width="50%"
    >
      <!-- 表单区域 -->
      <el-form ref="updateForm" :model="updateForm" :rules="updateFormRules" label-width="80px">
        <el-form-item prop="user" label="用户名">
          <el-input
            v-model="updateForm.user"
            prefix-icon="el-icon-user"
            :disabled="!updateForm.isCreate"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item prop="pass" label="密码" required v-if="updateForm.isCreate">
          <el-input v-model="updateForm.pass" prefix-icon="el-icon-unlock" disabled></el-input>
        </el-form-item>
        <el-form-item prop="limit" label="身份" required>
          <el-select
            v-model="updateForm.limit"
            placeholder="请选择身份类型"
            prefix-icon="el-icon-key"
            style="width:100%"
          >
            <el-option
              v-for="(name,limit) in $app.user.limit"
              :key="parseInt(limit)"
              :label="name"
              :value="parseInt(limit)"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="updateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateForm.isCreate?addUser():modifyUser()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      queryInfo: {
        keyword: '',
        page: 1,
        pageSize: 10,
      },
      total: 0,
      userList: [],
      inLoading: false,
      keyword: '',
      updateDialogVisible: false, //是否显示添加用户对话框
      updateForm: {},
      updateFormRules: {
        user: [
          { required: true, message: '请输入用户名', trigger: 'change' },
          {
            min: 3,
            max: 12,
            message: '长度在 3 到 12 个字符',
            trigger: 'change',
          },
          {
            validator: async (rule, value, callback) => {
              if (!this.updateForm.isCreate) callback()//修改直接跳过
              const exist = await this.isUserExist(value)
              if (exist) {
                callback(new Error('该用户已存在！'))
              } else {
                callback()
              }
            },
            trigger: 'blur',
          },
        ],
      },
    }
  },
  methods: {
    async getUserList() {
      const { data: res } = await this.$http.get('user', {
        params: this.queryInfo,
      })

      console.log(res)
      if (res.code !== this.$result.success)
        return this.$message.error('获取用户数据失败！')
      this.userList = res.data.list
      this.total = res.data.total
    },
    addUser() {
      this.$refs.updateForm.validate(async (valid) => {
        if (!valid) {
          return this.$message.error('用户信息不合法')
        }

        const { data: res } = await this.$http.post('user', this.updateForm)

        if (res.code !== this.$result.success) {
          return this.$message.error(res.msg)
        }
        this.$message.success(res.msg)
        this.updateDialogVisible = false
        this.getUserList()
      })
    },
    showUpdateDialog(user) {
      if (user) {
        this.updateForm = this.$app.clone(user)
        this.updateForm.isCreate = false
      } else {
        this.updateForm = this.$app.clone(this.$app.user.new)
        this.updateForm.isCreate = true
      }
      let updateForm = this.$refs.updateForm
      if (updateForm) updateForm.resetFields()
      this.updateDialogVisible = true
    },
    modifyUser() {
      this.$refs.updateForm.validate(async (valid) => {
        if (!valid) {
          return this.$message.error('用户信息不合法')
        }

        const { data: res } = await this.$http.put(`user`, this.updateForm)

        if (res.code !== this.$result.success) {
          return this.$message.error(res.msg)
        }
        this.$message.success(res.msg)
        this.updateDialogVisible = false
        this.getUserList()
      })
    },
    async resetPassword(user) {
      const { data: res } = await this.$http.put(`user/reset_password/${user}`)
      if (res.code !== this.$result.success) {
        return this.$message.error(res.msg)
      }
      this.$message.success(`${res.msg}\n密码已重置为：${res.data.newPass}`)
      this.updateDialogVisible = false
    },
    async removeUser(user) {
      try {
        await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })

        const { data: res } = await this.$http.delete(`user/${user}`)

        if (res.code !== this.$result.success) {
          return this.$message.error(res.msg)
        }
        this.$message.success(res.msg)
        this.getUserList()
      } catch {
        this.$message.info('已取消删除')
      }
    },
    async isUserExist(user) {
      const { data: res } = await this.$http.get(`user/is_exist/${user}`)
      if (res.code === this.$result.success) {
        return res.data
      } else {
        return false
      }
    },
  },
  watch: {
    queryInfo: {
      handler() {
        this.getUserList()
      },
      deep: true, //深度监视
    },
  },
  created() {
    this.getUserList()
  },
}
</script>

<style lang="less" scoped>
</style>